﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.PurchaseCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.PurchaseCommandHandler
{
    /// <summary>
    /// 采购详情添加命令处理
    /// </summary>
    public class PurchaseCreatedetailsCreateCommandHandler : IRequestHandler<PurchaseCreatedetailsCreateCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 采购
        /// </summary>
        private readonly IBaseRepository<Purchase> purchaseRepository;
        /// <summary>
        /// 详情
        /// </summary>
        private readonly IBaseRepository<Purchasedetails> purchaseDetailsRepository;

        public PurchaseCreatedetailsCreateCommandHandler(IMapper mapper, IBaseRepository<Purchase> purchaseRepository, IBaseRepository<Purchasedetails> purchaseDetailsRepository)
        {
            this.mapper = mapper;
            this.purchaseRepository = purchaseRepository;
            this.purchaseDetailsRepository = purchaseDetailsRepository;
        }

        public async Task<APIResult<object>> Handle(PurchaseCreatedetailsCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            PurchaseCreatedetailsCreateCommand add = new PurchaseCreatedetailsCreateCommand();

            string newCode = await GenerateOrderCodee();
            add.Purchaseid = request.Purchaseid;
            add.OrderCode = newCode;
            add.OrderName = request.OrderName;
            add.OrderType = request.OrderType;
            add.Project = request.Project;
            add.Supplier = request.Supplier;
            add.SignDate = request.SignDate;
            add.Maker = request.Maker;
            add.MakerDept = request.MakerDept;
            add.Status = request.Status;
            add.ApprovalStatus = request.ApprovalStatus;
            add.AgreementCode = request.AgreementCode;
            add.AgreementName = request.AgreementName;
            add.OrderRemark = request.OrderRemark;
            add.OrderAmount = request.OrderAmount;
            add.Currency = request.Currency;
            add.AdvancePayment = request.AdvancePayment;
            add.OrderStartDate = request.OrderStartDate;
            add.OrderEndDate = request.OrderEndDate;
            add.SignTime = request.SignTime;
            add.TaxType = request.TaxType;
            add.TaxRate = request.TaxRate;
            add.InvoiceAmount = request.InvoiceAmount;
            add.PaidAmount = request.PaidAmount;
            var info = mapper.Map<Purchase>(add);
            info.CreatedTime=DateTime.Now;
            var data = purchaseRepository.AddAsync(info).Result;
            if (data > 0)
            {
                request.Purchasedetailss.ForEach(o =>
                {
                    o.POrderCode = newCode;
                    o.MaterialId = request.Purchaseid;
                });
                var code= purchaseDetailsRepository.AddRanges(request.Purchasedetailss).Result;
                if(code > 0)
                {
                    result.Code = APIEnums.添加成功;
                    result.Msg = APIEnums.添加成功.ToString();
                    result.data = data;
                }
                else
                {

                    result.Code = APIEnums.添加失败;
                    result.Msg = APIEnums.添加失败.ToString();
                }
                
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
            }
            return await Task.FromResult(result);
        }

        // 编码生成方法（示例格式：PR-20240605-0045）
        private async Task<string> GenerateOrderCodee()
        {
            // 获取当天最大编码
            DateTime today = DateTime.Today;
            string datePart = today.ToString("yyyyMMdd");
            string prefix = $"PR-{datePart}-";

            var maxCode = await purchaseRepository.GetAll().Result
                           .Where(p => p.OrderCode.StartsWith(prefix))
                           .OrderByDescending(p => p.OrderCode)
                           .Select(p => p.OrderCode)
                           .FirstOrDefaultAsync();

            // 解析序列号
            int serialNumber = 1;
            if (!string.IsNullOrEmpty(maxCode))
            {
                string lastNumber = maxCode.Split('-').Last();
                if (int.TryParse(lastNumber, out int lastSerial))
                {
                    serialNumber = lastSerial + 1;
                }
            }

            // 格式化为4位数字
            return $"{prefix}{serialNumber:D4}";
        }
    }
}
